package com.shishuo.cms.tag;

import com.shishuo.cms.entity.vo.FolderVo;
import com.shishuo.cms.plugin.TagPlugin;
import com.shishuo.cms.service.FolderService;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateNumberModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;

import static freemarker.template.ObjectWrapper.DEFAULT_WRAPPER;

/**
 * 面包屑导航
 * 参数
 * folderid : 当前栏目id
 */
@Service
public class CrumbsNavTag extends TagPlugin {

    @Autowired
    private FolderService folderService;

    @Override
    public void execute(Environment environment, Map map, TemplateModel[] templateModels, TemplateDirectiveBody templateDirectiveBody) throws TemplateException, IOException {
        Long folderId = map.get("folderId") instanceof TemplateNumberModel ? ((TemplateNumberModel) map.get("folderId")).getAsNumber().longValue() : 0;
        List<FolderVo> list = folderService.getCrumbsFolder(folderId);
        Collections.reverse(list);
        environment.setVariable("crumbs_list", DEFAULT_WRAPPER.wrap(list));
        templateDirectiveBody.render(environment.getOut());
    }
}
